package dat255.calendarclock.controller.event;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;
import dat255.calendarclock.R;
import dat255.calendarclock.controller.event.activity.CreateCategoryActivity;
import dat255.calendarclock.controller.event.activity.DayPickerActivity;
import dat255.calendarclock.model.event.Category;
import dat255.calendarclock.model.event.CategoryComparator;
import dat255.calendarclock.model.event.Event;
import dat255.calendarclock.model.event.EventHandler;
import dat255.calendarclock.model.event.SubEvent;
import dat255.calendarclock.model.event.interval.OneTimeInterval;

/**
 * 
 * @author Gabriel Andersson
 * 
 */
public class EditEventController extends Activity {

	// The subEvent that is being edited
	private static SubEvent selectedEvent;

	// Fields
	private static boolean isInitialized = false;

	private static TextView titleText;
	private static EditText nameTextField;
	private static EditText descTextField;
	private static Spinner categorySpinner;
	private static ArrayAdapter<Category> categorySpinnerAdapter;
	private static Category newCategoryOption;
	private static Button editDateButton;
	private static TimePicker timePicker;
	private static CheckBox reccurringCheckBox;
	private static LinearLayout reccurringLayout;
	private static RadioButton weeklyRadioButton;
	private static RadioButton monthlyRadioButton;
	private static LinearLayout weeklyLayout;
	private static ToggleButton[] weeklyToggleButtons;
	private static LinearLayout monthlyLayout;
	private static Spinner recurringSpinner;
	private static ArrayAdapter<String> recurringWeeklyAdapter;
	private static ArrayAdapter<String> recurringMonthlyAdapter;
	private static ArrayList<String> recurringWeeklyOptions = new ArrayList<String>();
	private static ArrayList<String> recurringMonthlyOptions = new ArrayList<String>();
	private static Button saveButton;
	private static Button removeButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.modifyevent_layout);
		if (!isInitialized)
			init();
		resetFields();
	}

	@Override
	protected void onResume() {
		super.onResume();
		updateFields();
	}

	/**
	 * initializes the fields
	 */
	private void init() {
		// Event that is being edited is set
		selectedEvent = EventHandler.getInstance().getSelectedEvent();
		// Title
		titleText = (TextView) findViewById(R.id.eventDetails_Title);
		titleText.setText("Edit Event");
		// Name
		nameTextField = (EditText) findViewById(R.id.eventDetails_nameTextField);
		// Description
		descTextField = (EditText) findViewById(R.id.eventDetails_descTextField);
		// Category
		{
			newCategoryOption = Category.createCategory("New Category...",
					Color.WHITE);
			categorySpinner = (Spinner) findViewById(R.id.eventDetails_categorySpinner);
			categorySpinnerAdapter = new ArrayAdapter<Category>(
					getApplicationContext(),
					android.R.layout.simple_spinner_item,
					new ArrayList<Category>(EventHandler.getInstance()
							.getAllCategories()));
			categorySpinnerAdapter
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			// Standard values
			if (!(EventHandler.getInstance().getAllCategories()
					.contains(Category.createCategory()))) {
				categorySpinnerAdapter.add(Category.createCategory());
			}
			if (!(EventHandler.getInstance().getAllCategories()
					.contains(newCategoryOption)))
				categorySpinnerAdapter.add(newCategoryOption);
			categorySpinner.setAdapter(categorySpinnerAdapter);
			categorySpinner
					.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
						@Override
						public void onItemSelected(AdapterView<?> adapter,
								View view, int i, long lng) {
							if (i == EditEventController.categorySpinnerAdapter
									.getPosition(newCategoryOption)) {
								startActivity(new Intent(
										EditEventController.this,
										CreateCategoryActivity.class));
							}
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
						}

					});
		}
		// Date
		editDateButton = (Button) findViewById(R.id.eventDetails_dayPicker);
		// Time
		timePicker = (TimePicker) findViewById(R.id.eventDetails_timePicker);
		timePicker.setIs24HourView(true);
		// Recurring section
		{
			reccurringCheckBox = (CheckBox) findViewById(R.id.eventDetails_reccurringCheckBox);

			// Radio buttons
			weeklyRadioButton = (RadioButton) findViewById(R.id.eventDetails_weeklyRadioButton);
			monthlyRadioButton = (RadioButton) findViewById(R.id.eventDetails_monthlyRadioButton);
			// Layouts
			weeklyLayout = (LinearLayout) findViewById(R.id.eventDetails_weeklyLayout);
			monthlyLayout = (LinearLayout) findViewById(R.id.eventDetails_monthlyLayout);
			weeklyToggleButtons = new ToggleButton[] {
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonMon),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonTue),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonWed),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonThu),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonFri),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonSat),
					(ToggleButton) findViewById(R.id.eventDetails_weekdayButtonSun) };
			reccurringLayout = (LinearLayout) findViewById(R.id.eventDetails_reccurringLayout);
			recurringSpinner = (Spinner) findViewById(R.id.eventDetails_recurringSpinner);
			recurringWeeklyOptions.add(getString(R.string.every_week));
			recurringWeeklyOptions.add(getString(R.string.every_other_week));
			recurringWeeklyOptions.add(getString(R.string.every_third_week));
			recurringWeeklyOptions.add(getString(R.string.every_fourth_week));
			recurringWeeklyAdapter = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_spinner_item,
					recurringWeeklyOptions);
			recurringMonthlyOptions.add(getString(R.string.every_month));
			recurringMonthlyAdapter = new ArrayAdapter<String>(
					getApplicationContext(),
					android.R.layout.simple_spinner_item,
					recurringMonthlyOptions);
		}
		// End zone
		saveButton = (Button) findViewById(R.id.eventDetails_doneButton);
		removeButton = (Button) findViewById(R.id.eventDetails_removeEventButton);

	}

	/**
	 * Resets the fields to an initial value
	 */
	private void resetFields() {
		// Text fields
		nameTextField.setText(selectedEvent.getEvent().getName());
		descTextField.setText(selectedEvent.getEvent().getDescription());

		// Category
		categorySpinnerAdapter.sort(new CategoryComparator());
		categorySpinner.setSelection(categorySpinnerAdapter
				.getPosition(selectedEvent.getEvent().getCategory()));

		// Recurring
		reccurringCheckBox
				.setChecked(selectedEvent.getEvent().getInterval() instanceof OneTimeInterval ? false
						: true);
		weeklyRadioButton.setChecked(true);

		// end zone
		saveButton.setText("Edit Event");
		removeButton.setVisibility(View.VISIBLE);

		updateFields();

	}

	/**
	 * Updates the fields Call this when something has changed
	 */
	private void updateFields() {

		Category category = EventHandler.getInstance().getCustomCategory();
		if (category != null) {
			categorySpinnerAdapter.add(category);
			categorySpinnerAdapter.sort(new CategoryComparator());
			categorySpinner.setSelection(categorySpinnerAdapter
					.getPosition(category));
		}

		// Date
		editDateButton.setText(new SimpleDateFormat("dd MMMM yyyy")
				.format(EventHandler.getInstance().getSelectedDay().getTime()));
		// Time
		try {// TODO: remove this when pastEvent list is used.
			GregorianCalendar timeReference = EventHandler.getInstance()
					.getSelectedEvent().getEvent().getInterval().getFirst();
			timePicker.setCurrentHour(timeReference
					.get(GregorianCalendar.HOUR_OF_DAY));
			timePicker.setCurrentMinute(timeReference
					.get(GregorianCalendar.MINUTE));
		} catch (Exception e) {
			Log.d("debug",
					"Issues with the onetimeinterval. getting null since there are no past events. (Editevent)");
		}
		// Recurring Layouts
		reccurringLayout
				.setVisibility(reccurringCheckBox.isChecked() ? View.VISIBLE
						: View.GONE);
		weeklyLayout.setVisibility(weeklyRadioButton.isChecked() ? View.VISIBLE
				: View.GONE);
		int dayOfWeek = (EventHandler.getInstance().getSelectedDay()
				.get(GregorianCalendar.DAY_OF_WEEK) + 5) % 7;

		for (int i = 0; i < weeklyToggleButtons.length; i++) {
			if (i == dayOfWeek) {
				weeklyToggleButtons[i].setClickable(false);
				weeklyToggleButtons[i].setChecked(true);
			} else {
				weeklyToggleButtons[i].setClickable(true);
				if (!reccurringCheckBox.isChecked()) {
					weeklyToggleButtons[i].setChecked(false);
				}
			}

		}
		// TODO: monthly settings, yearly reccuring.
		// TODO: specified date must be marked in month
		monthlyLayout
				.setVisibility(monthlyRadioButton.isChecked() ? View.VISIBLE
						: View.GONE);
		recurringSpinner
				.setAdapter(weeklyRadioButton.isChecked() ? recurringWeeklyAdapter
						: recurringMonthlyAdapter);
		// TODO: OccurringSpinner Strings.

	}

	/**
	 * called when button for edit date is clicked
	 */
	public void editDateButtonClicked(View view) {
		startActivity(new Intent(this, DayPickerActivity.class));

	}

	/**
	 * called when check-box for recurring options is clicked
	 */
	public void reccuringCheckBoxClicked(View view) {
		updateFields();
	}

	/**
	 * called when radio button for weekly recurring is clicked
	 */
	public void weeklyRadioButtonClicked(View view) {
		updateFields();
	}

	/**
	 * called when radio button for monthly recurring is clicked
	 */
	public void monthlyRadioButtonClicked(View view) {
		updateFields();
	}

	/**
	 * If the edit event button is clicked this method is called
	 */
	public void doneButtonClicked(View view) {
		// Getting values from fields
		EventHandler eventHandler = EventHandler.getInstance();
		String name = nameTextField.getText().toString();
		String description = descTextField.getText().toString();
		Category category = categorySpinnerAdapter.getItem(categorySpinner
				.getSelectedItemPosition());
		GregorianCalendar date = eventHandler.getSelectedDay();
		date.set(GregorianCalendar.HOUR_OF_DAY, timePicker.getCurrentHour());
		date.set(GregorianCalendar.MINUTE, timePicker.getCurrentMinute());

		if (date.before(new GregorianCalendar())) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					EditEventController.this).create();
			alertDialog.setTitle("The destiny is unclear");
			alertDialog
					.setMessage("The time and date is somehow floating into the past eternity...");
			alertDialog.setButton("Back to the future", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			alertDialog.setIcon(R.drawable.icon);
			alertDialog.show();
			return;
		}

		// TODO: Disabled due to debugging
		// boolean reccuring = reccuringCheckBox.isChecked();
		// TODO: this doesn't look at the interval
		// TODO: Monthly interval..
		// TODO: Occurring different intervals of intervals.
		
		//Editing selected event
		Event event = selectedEvent.getEvent();
		event.setName(name);
		event.setDescription(description);
		event.setCategory(category);
		event.getInterval().setTimeOfEvent(timePicker.getCurrentHour(),
				timePicker.getCurrentMinute());

		Toast.makeText(getApplicationContext(), "Your event has been modified",
				Toast.LENGTH_LONG).show();

		EditEventController.this.finish();
		
	}

	public void removeButtonClicked(View view) {
		new AlertDialog.Builder(EditEventController.this)
				.setNegativeButton("No!", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

					}
				})
				.setPositiveButton("Yes I do!", new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						EventHandler.getInstance().removeEvent(
								selectedEvent.getEvent());
						EventHandler.getInstance().setSelectedEvent(null);

						EditEventController.this.finish();
					}
				}).setTitle("Warning!")
				.setMessage("Do you really want to remove this event?")
				.create().show();
	}
}
